<?php

namespace common\modules\wechat\widgets;

use common\helpers\Html;
use common\modules\wechat\models\ReplyKeyword;
use common\modules\wechat\models\ReplyRule;
use common\widgets\DateTimePicker;
use common\widgets\DynamicForm;
use yii\bootstrap\Widget;
use yii\helpers\ArrayHelper;

class ReplyKeywordDynamicForm extends Widget
{

    public $attribute;

    public $form;

    public $model;

    public $formOptions = [];

    /**
     * @var array
     */
    public $defaultFormOptions = [
        'widgetContainer' => 'reply_keyword_dynamic_form_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
        'widgetBody'      => '.container-items', // required: css class selector
        'widgetItem'      => '.item', // required: css class
        'limit'           => 4, // the maximum times, an element can be cloned (default 999)
        'min'             => 1, // 0 or 1 (default 1)
        'insertButton'    => '.add-item', // css class
        'deleteButton'    => '.remove-item', // css class
        'formFields'      => [
            'award_id',
            'num',
            'probability',
            'sort',
        ],
    ];

    /**
     * {@inheritdoc}
     */
    public function init()
    {
        parent::init();

        $this->formOptions = ArrayHelper::merge($this->defaultFormOptions, $this->formOptions);
    }

    /**
     * {@inheritdoc}
     */
    public function run()
    {
        parent::run();
        $this->renderDynamicForm($this->form, $this->model);
    }

    /**
     * @param ActiveForm $form
     * @param ReplyRule $model
     * @return string
     */
    public function renderDynamicForm($form, $model)
    {
        /** @var ReplyKeyword[] $keywords */
        $keywords = $model->keywords;

        // 保证奖品不为空
        if (empty($keywords))
        {
            $keyword = new ReplyKeyword;;
            $keyword->priority = 0;
            $keywords = [$keyword];
        }

        ?>
        <?php DynamicForm::begin($this->formOptions); ?>

        <table id="reply-keyword-dynamic-table" class="container-items table table-bordered" style="table-layout: fixed;">
            <thead>
                <tr>
                    <th width="160">关键字类型</th>
                    <th>规则关键字</th>
                    <th>开始时间</th>
                    <th>结束时间</th>
                    <th width="80">优先级</th>
                    <th width="90">操作</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($keywords as $i => $keyword): ?>
                <tr class="item panel panel-default">
                    <?php
                    // necessary for update action.
                    if ( ! $keyword->isNewRecord)
                    {
                        echo Html::activeHiddenInput($keyword, "[{$i}]id");
                    }
                    ?>
                    <td>
                        <?php echo $form->field($keyword, "[{$i}]type", ['parts' => ['{label}' => '']])->dropDownList(ReplyKeyword::$types) ?>
                    </td>
                    <td>
                        <?= $form->field($keyword, "[{$i}]keyword", ['parts' => ['{label}' => '']])->textInput(['maxlength' => true]) ?>
                    </td>
                    <td>
                        <?= $form->field($keyword, "[{$i}]start_at", ['parts' => ['{label}' => '']])->widget(DateTimePicker::className(), [
                            'options' => ['placeholder' => '选择开始时间'],
                            'overrideAttribute' => 'start_at',
                        ]) ?>
                    </td>
                    <td>
                        <?= $form->field($keyword, "[{$i}]end_at", ['parts' => ['{label}' => '']])->widget(DateTimePicker::className(), [
                            'options' => ['placeholder' => '选择结束时间'],
                            'overrideAttribute' => 'end_at',
                        ]) ?>
                    </td>
                    <td>
                        <?= $form->field($keyword, "[{$i}]priority", ['parts' => ['{label}' => '']])->textInput(['maxlength' => true]) ?>
                    </td>
                    <td>
                        <button type="button" class="add-item btn btn-success btn-sm">
                            <i class="glyphicon glyphicon-plus"></i>
                        </button>
                        <button type="button" class="remove-item btn btn-danger btn-sm">
                            <i class="glyphicon glyphicon-minus"></i>
                        </button>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>

        <?php DynamicForm::end(); ?>

        <div class="alert alert-warning">请在管理员指导下使用上面的编辑功能!</div>

        <?php

        $this->view->registerCss('
        #reply-keyword-dynamic-table .form-group { margin-bottom:0; }
        #reply-keyword-dynamic-table .help-block { margin-bottom:0; }
        ');
        $this->view->registerJs('
$(".reply_keyword_dynamic_form_wrapper").on("beforeInsert", function(e, item) {
    console.log("beforeInsert");
});
$(".reply_keyword_dynamic_form_wrapper").on("afterInsert", function(e, item) {
    console.log("afterInsert");
});
$(".reply_keyword_dynamic_form_wrapper").on("beforeDelete", function(e, item) {
    if (! confirm("是否确认要删除该关键词?")) {
        return false;
    }
    return true;
});
$(".reply_keyword_dynamic_form_wrapper").on("afterDelete", function(e) {
    console.log("成功删除!");
});
$(".reply_keyword_dynamic_form_wrapper").on("limitReached", function(e, item) {
    alert("到达上限!");
});
        ');
    }
}
